// const baseURL = "http://172.16.13.17:80";
const baseURL = "http://HKF-WORK-PC:8083";
// const baseURL = "http://192.168.0.23:8089";

// 用于防抖
const set = new Set<string>();

import { load, save } from "./localcache";

function ajax(url: string, data: object = {}, method: "POST" | "GET" = "POST"): Promise<any> {
  let jsonStr = JSON.stringify(data);
  let key = url + jsonStr + method;

  // 缓存数据
  let obj = load(key);
  if (null != obj) {
    return Promise.resolve({ data: obj });
  }

  if (set.has(key)) {
    console.log("请勿重复提交：",key);
    return Promise.reject({ data: { code: 1, msg: "请勿重复提交" } });
  }

  set.add(key);

  // 一分钟之后移除掉（兜底）
  // setTimeout(() => set.delete(url),60 * 1000);
  return new Promise((resolve, reject) => {
    wx.request(
      {
        url: `${baseURL}${url}`,
        data,
        method,
        header: {
          Authorization: wx.getStorageSync("token")
        },
        success(res: any) {
          // 失败弹窗
          if (res.data.status < 0) {
            wx.showToast({
              title: res.data.msg,
              icon: "error",
            })
          } else {
            // 成功：记录缓存
            save(url,jsonStr,method,res.data);
            resolve(res);
          }
        },
        fail(res) {
          console.log(res)
          reject({ data: { code: 1, msg: "网络错误" } });
          wx.showToast({
            title: "网络错误",
            icon: "error",
          })
        },
        // 无论如何都执行
        complete() {
          set.delete(key);
        }
      }
    )
  })
}

export default ajax;